<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">欢迎登录XXX系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="用户名"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-form-item
        v-if="loginValidateType==='viewPictureText'"
        prop="viewPictureText"
      >
        <span class="svg-container">
          <i class="el-icon-picture-outline-round" />
        </span>
        <el-input
          v-model="loginForm.code"
          placeholder="验证码"
          tabindex="3"
          auto-complete="on"
        />
        <span class="show-pwd">
          <el-image
            title="点击更换图片"
            style="border-radius: 2px"
            :src="baseUrl+'/userAuth/getImageTextVerifyCode?uid='+loginForm.uid"
            @click="getUuidData()"
          />
        </span>
      </el-form-item>

      <!--      <l-button-->
      <!--        ref="loginBtn"-->
      <!--        auto-loading-->
      <!--        type="primary"-->
      <!--        style="width:100%;margin-bottom:30px;"-->
      <!--        @click="handleLogin"-->
      <!--      >登录</l-button>-->

      <!--      <div class="tips">-->
      <!--        <span style="margin-right:20px;">username: admin</span>-->
      <!--        <span> password: any</span>-->
      <!--      </div>-->

    </el-form>
    <div style="width: 100vw;text-align: center;">
      <l-button
        ref="loginBtn"
        auto-loading
        type="primary"
        style="width:450px;margin: 0 auto;"
        @click="handleLogin"
      >登录</l-button>
    </div>
    <ImageVerifyCode ref="imageVerifyCode" @close="imageVerifyCodeClose()" @checkOffset="checkOffset" />
  </div>
</template>

<script>
import {
  getLoginValidateType,
  getImageTextVerifyCode
} from '@/api/user'
import ImageVerifyCode from '@/components/imageVerifyCode/ImageVerifyCode'
import { getUuid } from '@/utils/index'
import LButton from '@/components/loadingButton/LButton'

export default {
  name: 'Login',
  components: {
    LButton, ImageVerifyCode
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码最少六位'))
      } else {
        callback()
      }
    }
    const validatePictureText = (rule, value, callback) => {
      if (
        this.loginValidateType === 'viewPictureText' &&
        !this.loginForm.code
      ) {
        callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: '',
        w: '',
        h: '',
        code: '',
        uid: getUuid()
      },
      showCode: false,
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        viewPictureText: [{ required: true, trigger: 'blur', validator: validatePictureText }]
      },
      passwordType: 'password',
      redirect: undefined,
      loginValidateType: null,
      imageTextCode: '',
      baseUrl: process.env.VUE_APP_BASE_API
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    if (process.env.NODE_ENV === 'development') {
      this.loginForm.username = 'admin'
      this.loginForm.password = '111111'
    }
    this.getLoginValidateTypeData()
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    mouseover() {
      this.showCode = true
    },
    mouseLeave() {
      this.showCode = false
    },
    getUuidData() {
      this.loginForm.uid = getUuid()
    },
    imageVerifyCodeClose() {
      this.$refs['loginBtn'].setLoadingStatusFalse()
    },
    checkOffset(offsetVal, uid) {
      this.loginForm.uid = uid
      this.loginForm.w = offsetVal.w
      this.loginForm.h = offsetVal.h
      this.$refs['imageVerifyCode'].showLoading()
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$store.dispatch('user/login', this.loginForm).then(() => {
            // this.$loading({
            //   lock: true,
            //   text: '登录中，请稍候...',
            //   spinner: 'el-icon-loading',
            //   background: 'rgba(0, 0, 0, 0.7)'
            // });

            this.$router.push({ path: this.redirect || '/' })
          }).catch(() => {
            this.$refs['imageVerifyCode'].closeLoading()
            this.$refs['imageVerifyCode'].reset()
          }).finally(() => {
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleLogin(next) {
      if (this.loginValidateType === 'imageDrag') {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.$refs['imageVerifyCode'].open()
          } else {
            console.log('error submit!!')
            next()
            return false
          }
        })
      } else if (this.loginValidateType === 'viewPictureText') {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            // debugger
            this.$store.dispatch('user/login', this.loginForm).then(() => {
              this.$router.push({ path: this.redirect || '/' })
            }).catch(() => {
              this.getUuidData()
            }).finally(() => {
              next()
            })
          } else {
            next()
            return false
          }
        })
      } else if (this.loginValidateType === 'none') {
        this.$store.dispatch('user/login', this.loginForm).then(() => {
          this.$router.push({ path: this.redirect || '/' })
        }).catch(() => {
          this.getUuidData()
        }).finally(() => {
          next()
        })
      }
    },
    getLoginValidateTypeData() {
      getLoginValidateType().then(res => {
        this.loginValidateType = res.obj
      })
    },
    getImageTextVerifyCodeData() {
      getImageTextVerifyCode().then(res => {
        this.imageTextCode = res.data
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(96, 125, 139, 0.50);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#fff;

.login-container {
  min-height: 100%;
  width: 100%;
  //background-color: $bg;
  background-image: url("/img/bg.jpg");
  background-repeat: round;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    //color: $dark_gray;
    color: #e1f5fe;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
